package com.cx.bank.manager;

import com.cx.bank.dao.BankDaoImpl;
import com.cx.bank.dao.BankDaoInterface;
import com.cx.bank.exception.AccountOverDrawnException;
import com.cx.bank.exception.InvalidDepositException;
import com.cx.bank.pojo.User;

import java.io.IOException;
import java.sql.SQLException;
import java.util.List;

/**
 * @author jxau_scf
 * @date 2021/7/13 - 20:39
 */
public class ManagerImpl implements IManager {
    //默认注入一个BankDaoImpl()
    private BankDaoInterface bankDao = new BankDaoImpl();

    /**
     *查询余额方法
     * @return
     */
    @Override
    public Double inquiry(String userName) throws SQLException {
        User user = bankDao.findByName(userName);
        return user.getBalance();
    }

    /**
     * 通过用户名查找用户
     * @param userName
     * @return
     * @throws SQLException
     */
    @Override
    public User findUserByName(String userName) throws SQLException {
        return bankDao.findByName(userName);
    }

    @Override
    public User findUserByUserId(Integer userId) throws SQLException {
        return bankDao.findUserByUserId(userId);
    }

    /**
     * 查询所有用户
     * @return
     * @throws SQLException
     */
    @Override
    public List<User> findAllUser() throws SQLException {
        return bankDao.findAllUser();
    }

    @Override
    public boolean updateUser(User user) {
        return bankDao.updateUser(user);
    }

    @Override
    public boolean deleteUserByUserId(Integer userId) {
        return bankDao.deleteUserByUserId(userId);
    }


    /**
     * 取款方法（实现“余额不足”逻辑判断）
     */
    @Override
    public boolean withdrawals(String userName, Double money) throws InvalidDepositException, SQLException {
        User user = bankDao.findByName(userName);
        double currentMoney = user.getBalance();
        if (currentMoney < money){
            throw new InvalidDepositException("余额不足");
        }
//        user.setBalance(currentMoney - money);
        //更新到数据库
        boolean updateMoneyStatus = bankDao.updateMoney(userName, currentMoney - money);
        //日志记录
//        if (updateMoneyStatus) {
//            User userInDB = bankDao.findByName(userName);
//            Log log = new Log();
//            log.setLogType("withdrawals");
//            log.setLogAmount(money);
//            log.setUserId(userInDB.getUserId());
//            LogUtil.insertLog(log);
//        }
        return updateMoneyStatus;
    }

    /**
     * 存款方法（实现“存款不能为负”逻辑判断）
     */
    @Override
    public boolean deposit(String userName, double money) throws AccountOverDrawnException, SQLException {
        if (money < 0){
            throw new AccountOverDrawnException("存款不能为负");
        }
        User user = bankDao.findByName(userName);
        Double currentMoney = user.getBalance();
        boolean updateMoneyStatus = bankDao.updateMoney(userName, currentMoney + money);
        //日志记录
//        if (updateMoneyStatus) {
//            User userInDB = bankDao.findByName(userName);
//            Log log = new Log();
//            log.setLogType("deposit");
//            log.setLogAmount(money);
//            log.setUserId(userInDB.getUserId());
//            LogUtil.insertLog(log);
//        }
        return updateMoneyStatus;
    }

    /**
     * 退出系统方法
     */
    @Override
    public void exitSystem() throws IOException {
        System.exit(1);
    }

    /**
     * 注册功能
     * @param user
     * @throws IOException
     */
    @Override
    public boolean register(User user) throws SQLException {
        User userInfoInDB = bankDao.findByName(user.getUserName());
        if (userInfoInDB != null){
            System.out.println("用户已存在");
            return false;
        }else {
            boolean status = bankDao.insertUser(user);
            //日志记录
//            if (status) {
//                User userInDB = bankDao.findByName(user.getUserName());
//                Log log = new Log();
//                log.setLogType("register");
//                log.setLogAmount(user.getBalance());
//                log.setUserId(userInDB.getUserId());
//                LogUtil.insertLog(log);
//            }
            return status;
        }
    }

    /**
     * 登录
     * @param userName
     * @param password
     * @return
     * @throws SQLException
     */
    @Override
    public boolean login(String userName, String password) throws SQLException {
        User user = bankDao.findUser(userName, password);
        if (user == null){
            return false;
        }else {
            return true;
        }
    }

    /**
     * 冻结账户
     * @param myUserName
     * @param toUserName
     * @param userFlag
     * @return
     * @throws SQLException
     */
    @Override
    public boolean frozenAccount(String myUserName, String toUserName, Integer userFlag) throws SQLException {
        if (myUserName == null || toUserName == null || userFlag == null){
            return false;
        }
        //判断当前用户是否有管理员权限
        User myUser = bankDao.findByName(myUserName);
        //01代表管理员，00代表普通用户
        if ("01".equals(myUser.getUserType())){
            boolean frozenAccountStatus = bankDao.updateUserFlag(toUserName, userFlag);
            //日志记录
//            if (frozenAccountStatus) {
//                User myUserInDB = bankDao.findByName(myUserName);
//                User toUserInDB = bankDao.findByName(toUserName);
//                Log log1 = new Log();
//                log1.setLogType("frozenAccount,操作冻结");
//                log1.setLogAmount(toUserInDB.getBalance());
//                log1.setUserId(myUserInDB.getUserId());
//                LogUtil.insertLog(log1);
//
//                Log log2 = new Log();
//                log2.setLogType("frozenAccount,被冻结");
//                log2.setLogAmount(toUserInDB.getBalance());
//                log2.setUserId(toUserInDB.getUserId());
//                LogUtil.insertLog(log2);
//            }
            return frozenAccountStatus;
        }else {
            System.out.println("当前用户没有冻结账户权限！");
            return false;
        }
    }


    /**
     * 转账功能
     * @param myUserName
     * @param toUserName
     * @param transferMoney
     * @return
     * @throws IOException
     * @throws SQLException
     */
    @Override
    public boolean transfer(String myUserName, String toUserName, double transferMoney) throws IOException, SQLException {
//        本账户
        User myUser = bankDao.findByName(myUserName);
        if (myUser == null){
            System.out.println("个人账户不存在，转账失败");
            return false;
        }
//        对方账户
        User toUser = bankDao.findByName(toUserName);
        if (toUser == null){
            System.out.println("该用户不存在，转账失败");
            return false;
        }
        if (myUserName.equals(toUserName)){
            System.out.println("不能给自己转账");
            return false;
        }
        if (transferMoney <= 0){
            System.out.println("转账金额不能低于0元");
            return false;
        }
        double leftMoney = myUser.getBalance();
        if (leftMoney < transferMoney){
            System.out.println("余额不足，不可转账");
            return false;
        }
        //本账户金额减少
        boolean status1 = bankDao.updateMoney(myUserName, leftMoney - transferMoney);
        if (status1){
            //添加日志记录
//            Log log1 = new Log();
//            log1.setLogType("transfer,本账户金额减少");
//            log1.setLogAmount(transferMoney);
//            log1.setUserId(myUser.getUserId());
//            LogUtil.insertLog(log1);


            Double toUserMoney = toUser.getBalance();
            //对方账户金额增加
            boolean status2 = bankDao.updateMoney(toUserName, toUserMoney + transferMoney);
            if (status2) {
                //添加日志记录
//                Log log2 = new Log();
//                log2.setLogType("transfer,转账账户金额增加");
//                log2.setLogAmount(transferMoney);
//                log2.setUserId(toUser.getUserId());
//                LogUtil.insertLog(log2);
            }
            return status2;
        }else {
            return false;
        }
    }
}
